//
//  XMIndexHeaderView.m
//  xiaorizi
//
//  Created by new-1020 on 2017/4/18.
//  Copyright © 2017年 begmoon. All rights reserved.
//

#import "XMIndexHeaderView.h"
#import "XMIndexCollectionViewCell.h"
#import "UIView+SGExtension.h"

#define SG_COLOR_RGB(rgbValue)  [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
#define SG_COLOR(R,G,B,A)   [UIColor colorWithRed:(R) / 255.0 green:(G) / 255.0 blue:(B) / 255.0 alpha:A]

#define lineH 3
#define insetRight 10
#define insetLeft 20

@interface XMIndexCollectionView()
@property(nonatomic,assign)CGFloat lastContentWidth;
@end

@implementation XMIndexCollectionView

-(void)layoutSubviews {
    [super layoutSubviews];
    if (self.lastContentWidth != self.contentSize.width) {
        if (self.resizeBlock) {
            self.resizeBlock();
        }
        self.lastContentWidth = self.contentSize.width;
    } else {
        return;
    }
}
@end


@interface XMIndexHeaderView()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property (nonatomic,strong) UIView *lineView;


@end

@implementation XMIndexHeaderView

-(UIView *)lineView {
    if (_lineView == nil) {
        if ([self.delegateXM respondsToSelector:@selector(customLineView)]) {
            _lineView = [self.delegateXM customLineView];
        } else {
            _lineView = [[UIView alloc]init];
        }
    }
    return _lineView;
}

-(void)setHideLine:(BOOL)hideLine {
    _hideLine = hideLine;
    if (hideLine) {
        self.lineView.hidden = YES;
    }else {
        self.lineView.hidden = NO;
    }
}

-(instancetype)initWithFrame:(CGRect)frame WithTitleArray:(NSArray *)titleArray animation:(BOOL)animation {
    if (self = [super initWithFrame:frame]) {
        self.titleArray = titleArray;
        self.AnimationIsOpen = animation;
        [self creatUIWithTitleArray:titleArray];
    }
    return self;
}

-(instancetype)initWithFrame:(CGRect)frame WithTitleArray:(NSArray *)titleArray animation:(BOOL)animation delegate:(id<XMIndexHeaderViewDelegate>)delegate {
    if (self = [super initWithFrame:frame]) {
        self.delegateXM = delegate;
        self.titleArray = titleArray;
        self.AnimationIsOpen = animation;
        [self creatUIWithTitleArray:titleArray];
    }
    return self;
}

-(void)setChangeTitleArray:(NSArray *)changeTitleArray {
    _changeTitleArray = changeTitleArray;
    self.titleArray = changeTitleArray;
    if (self.collectionView) {
        [self.collectionView removeFromSuperview];
    }
    [self creatUIWithTitleArray:self.titleArray];
}

-(void)setChangeTitleArrayNotRefresh:(NSArray *)changeTitleArrayNotRefresh {
    _changeTitleArrayNotRefresh = changeTitleArrayNotRefresh;
    self.titleArray = changeTitleArrayNotRefresh;
    [self.collectionView reloadData];
    [self.collectionView layoutSubviews];
    [self layoutIfNeeded];
    [self fixLineView];
}


-(void)creatUIWithTitleArray:(NSArray *)titleArray {
    self.currentINdex = 0;
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    if (self.AnimationIsOpen == YES) {
        layout.sectionInset = self.inset;//UIEdgeInsetsMake(0, 0, 0, 0);
        layout.minimumLineSpacing = self.minimumLineSpacing;
    }else {
        layout.minimumLineSpacing = self.minimumLineSpacing;
    }
    self.collectionView = [[XMIndexCollectionView alloc]initWithFrame:self.bounds collectionViewLayout:layout];
    __weak typeof(self) weakSelf = self;
    [self.collectionView setResizeBlock:^{
        [weakSelf fixLineView];
    }];
    [self registerNib];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.backgroundColor = self.backGroundColor ? self.backGroundColor : [UIColor whiteColor];
    [self addSubview:self.collectionView];
    self.lineView.frame = CGRectMake(0, self.sgSize.height - lineH, 32, lineH);
    [self.collectionView addSubview:self.lineView];
    self.lineView.backgroundColor = SG_COLOR(245, 70, 70, 1);
    if (!self.AnimationIsOpen) {
        self.collectionView.bounces = NO;
        self.lineView.sgCenterX = [self GetSize].width / 2;
    }else {
        self.lineView.sgCenterX = [self GetSize].width / 2 + 10;
    }
   
    
}


-(void)registerNib {
    [self.collectionView registerNib:[UINib nibWithNibName:@"XMIndexCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"Cell"];
    if (self.config.customCell) {
        [self.collectionView registerNib:self.config.customCell forCellWithReuseIdentifier:@"customCell"];
    }
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.shouldAspect) {
        if (self.delegateXM && [self.delegateXM respondsToSelector:@selector(customCellSizeForItemAtIndexPath:)]) {
            return [self.delegateXM customCellSizeForItemAtIndexPath:indexPath];
        }
//        [SGAppHelper ];
        NSString * str = self.titleArray[indexPath.row];
        UIFont * font = [UIFont systemFontOfSize:16];
        if (self.config.font) {
            font = self.config.font;
        }
        if (self.currentINdex == indexPath.row && self.config.selectFont) {
                font = self.config.selectFont;
        }
        CGFloat width = [self TitleSize:str height:self.frame.size.height - lineH - 1 Width:MAXFLOAT Font:font].width + (self.config ? self.config.cellMargin : 0);
        
        id num = self.readCountDic[[NSString stringWithFormat:@"%ld",indexPath.row]];
        CGFloat numWidth = 0;
        if (num && [num integerValue] > 0) {
            numWidth = [self TitleSize:[NSString stringWithFormat:@"%ld", [num integerValue]] height:22 Width:MAXFLOAT Font:[UIFont systemFontOfSize:16]].width + 4;
        }
        return CGSizeMake(width + numWidth, self.frame.size.height - lineH - 1);
    }
    return self.itemSize.height > 0 ? self.itemSize : [self GetSize];
}

-(CGSize)GetSize {
    if (self.titleArray.count < 5) {
        return CGSizeMake(self.frame.size.width / self.titleArray.count, self.frame.size.height - lineH - 1);
    }else {
        return CGSizeMake(self.frame.size.width / 5, self.frame.size.height - lineH -1);
    }
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.titleArray.count;
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return self.minimumLineSpacing;
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return  self.minimumLineSpacing;
}

- (UIEdgeInsets) collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    if (self.inset.left > 0 || self.inset.right > 0) {return  self.inset;}
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.config.customCell) {
        UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"customCell" forIndexPath:indexPath];
        if (self.delegateXM && [self.delegateXM respondsToSelector:@selector(customCell:cellForItemAtIndexPath:selectIndex:title:)]) {
            [self.delegateXM customCell:cell cellForItemAtIndexPath:indexPath selectIndex:self.currentINdex title:self.titleArray[indexPath.row]];
        }
        return  cell;
    }
    else {
        XMIndexCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor whiteColor];
        cell.titleLable.text = self.titleArray[indexPath.row];
        if (self.config.font) {
            cell.titleLable.font = self.config.font;
        }
        if (self.currentINdex == indexPath.row) {
            cell.titleLable.textColor = [UIColor colorWithRed:245.0 / 255.0 green:70.0 / 255.0 blue: 70.0 / 255.0 alpha:1];
            if (self.config.selectFontColr) {
                cell.titleLable.textColor = self.config.selectFontColr;
            }
            if (self.config.selectFont) {
                cell.titleLable.font = self.config.selectFont;
            }
            if (self.selectItemColor) {
                cell.contentView.backgroundColor = self.selectItemColor;
            }
        }else {
            cell.titleLable.textColor = [UIColor blackColor];
            if (self.config.fontColor) {
                cell.titleLable.textColor = self.config.fontColor;
            }
            if (self.unselectItemColor) {
                cell.contentView.backgroundColor = self.unselectItemColor;
            }
        }
        if (self.backGroundColor) {
            cell.backgroundColor = self.backGroundColor;
        }
        
        // 描述红点
        id num = self.readCountDic[[NSString stringWithFormat:@"%ld",indexPath.row]];
        if (num && [num integerValue] > 0) {
            cell.countLabel.hidden = NO;
            cell.countLabel.text = [NSString stringWithFormat:@"%ld",[num integerValue]];
        } else {
            cell.countLabel.hidden = YES;
        }
        // 配置文件相关描述
        if (self.config) {
            cell.contentView.layer.cornerRadius = self.config.cellCornerRadius;
            if (self.config.cellCornerRadius > 0) {
                cell.contentView.layer.masksToBounds = YES;
            }
            cell.contentView.layer.borderWidth = self.config.cellBorderWidth;
            cell.contentView.layer.borderColor = self.currentINdex == indexPath.row ? self.config.cellSelectBorderColor.CGColor : self.config.cellBorderColor.CGColor;
        }
        return cell;
    }
    
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == self.currentINdex) {
        return;
    }
    
    if ([self.delegateXM respondsToSelector:@selector(XMIndexHeaderViewShouldScrollToIndex:indexView:)] && ![self.delegateXM XMIndexHeaderViewShouldScrollToIndex:indexPath.row indexView:self]) {
        return;
    }
    
    UICollectionViewCell * cell = [collectionView cellForItemAtIndexPath:indexPath];
    [UIView animateWithDuration:0.2 animations:^{
        self.lineView.sgCenterX = cell.center.x;
    }];
    if (self.AnimationIsOpen) {
         [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
    }
    self.currentINdex = indexPath.row;
    if ([self.delegateXM respondsToSelector:@selector(XMIndexHeaderViewDidselectedWithIndex:)]) {
        [self.delegateXM XMIndexHeaderViewDidselectedWithIndex:indexPath.row];
    }
    if ([self.delegateXM respondsToSelector:@selector(XMIndexHeaderViewDidselectedWithIndex:indexView:)]) {
        [self.delegateXM XMIndexHeaderViewDidselectedWithIndex:indexPath.row indexView:self];
    }
    
    [self.collectionView reloadData];
}

-(void)didselectRow:(NSInteger)row {
    [self collectionView:self.collectionView didSelectItemAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0]];
}

-(CGSize)TitleSize:(NSString *)str height:(CGFloat)height Width:(CGFloat)width Font:(UIFont *)font{
    CGSize contentStrSize = [str boundingRectWithSize:CGSizeMake(width,height)
                                              options:NSStringDrawingUsesLineFragmentOrigin
                                           attributes:@{NSFontAttributeName: font}
                                              context:nil].size;
    return contentStrSize;
}

-(void)LineViewScrolleToIndex:(NSInteger)index{
    [self LineViewScrolleToIndex:index animation:YES];
}


-(void)LineViewScrolleToIndex:(NSInteger)index animation:(BOOL)animation {
    if (index == self.currentINdex) {
        return;
    }
    [self RealLineViewScrolleToIndex:index animation:animation];
}

-(void)fixLineView {
    [self RealLineViewScrolleToIndex:self.currentINdex animation:NO];
}

-(void)RealLineViewScrolleToIndex:(NSInteger)index animation:(BOOL)animation {
//      if (self.AnimationIsOpen) {
              UICollectionViewCell * cell = [self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
            UICollectionViewLayoutAttributes * attri = [self.collectionView.collectionViewLayout layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
            CGFloat center = attri.frame.size.width / 2 + attri.frame.origin.x;
            if (animation) {
               [UIView animateWithDuration:0.2 animations:^{
                   self.lineView.sgCenterX = center;
               }];
            } else {
               self.lineView.sgCenterX = cell.center.x;
            }
            [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:animation];
//         } else {
//             if (animation) {
//               [UIView animateWithDuration:0.2 animations:^{
//                   self.lineView.sgCenterX =  [self GetSize].width / 2 + index * [self GetSize].width;
//               }];
//              } else {
//               self.lineView.sgCenterX =  [self GetSize].width / 2 + index * [self GetSize].width;
//             }
//         }
         self.currentINdex = index;
         [self.collectionView reloadData];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    UICollectionViewCell * cell = [self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    UICollectionViewLayoutAttributes * attri = [self.collectionView.collectionViewLayout layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    NSLog(@"%@----------%@", NSStringFromCGRect(attri.frame), NSStringFromCGRect(cell.frame));
}

-(void)setLineColor:(UIColor *)lineColor {
    lineColor = lineColor;
    self.lineView.backgroundColor = lineColor;
}

-(void)setLineWidth:(CGFloat )lineWidth {
    _lineWidth = lineWidth;
    self.lineView.sgWidth = lineWidth;
    self.lineView.sgCenterX = self.itemSize.width > 0 ? self.itemSize.width / 2 : [self GetSize].width / 2;
}


-(void)setItemSize:(CGSize)itemSize {
    _itemSize = itemSize;
    [self.collectionView reloadData];
}

-(void)setMinimumLineSpacing:(CGFloat)minimumLineSpacing {
    _minimumLineSpacing = minimumLineSpacing;
    [self.collectionView reloadData];
}

-(void)setSelectItemColor:(UIColor *)selectItemColor {
    _selectItemColor = selectItemColor;
    [self.collectionView reloadData];
}

-(void)setUnselectItemColor:(UIColor *)unselectItemColor {
    _unselectItemColor = unselectItemColor;
    [self.collectionView reloadData];
}

#pragma -mark:背景色
-(void)setBackGroundColor:(UIColor *)backGroundColor {
    _backGroundColor = backGroundColor;
    self.backgroundColor = backGroundColor;
    self.collectionView.backgroundColor = backGroundColor;
    [self.collectionView reloadData];
}

// lineViewYset
-(void)setLineViewYset:(CGFloat)lineViewYset {
    self.lineView.sgY += lineViewYset;
}

-(void)setShouldAspect:(BOOL)shouldAspect {
    _shouldAspect = shouldAspect;
    [self.collectionView reloadData];
}

- (void)setInset:(UIEdgeInsets)inset {
    _inset = inset;
    [self.collectionView reloadData];
}

/**
 * 红点添加
 */
-(NSMutableDictionary *)readCountDic {
    if (_readCountDic == nil) {
        _readCountDic = [[NSMutableDictionary alloc]init];
    }
    return _readCountDic;
}

-(void)setReadCount:(NSInteger)num withRow:(NSInteger)row {
    self.readCountDic[[NSString stringWithFormat:@"%ld",row]] = @(num);
    [self.collectionView reloadData];
}

#pragma -mark:配置文件配置
-(void)setConfig:(XMIndexHeaerViewConfig *)config {
    _config = config;
    if (config.customCell) {
        [self.collectionView registerNib:config.customCell forCellWithReuseIdentifier:@"customCell"];
    }
    self.lineView.layer.cornerRadius = config.lineViewCornerRadius;
    [self.collectionView reloadData];
}

-(void)setLineViewAlpha:(CGFloat)lineViewAlpha {
    _lineViewAlpha = lineViewAlpha;
    self.lineView.alpha = lineViewAlpha;
}
@end


